#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <QKeySequence>
#include <Windows.h>
#include <QDebug>
#include <QCoreApplication>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)    
{
    ui->setupUi(this);

    adjustSize();

    QCoreApplication::instance()->installNativeEventFilter(&m_filter);
    m_filter.setWidget(this);
    QObject::connect(ui->btnApply, SIGNAL(clicked()), this, SLOT(onApplyButtonClicked()));
    QObject::connect(ui->btnCancel, SIGNAL(clicked()), this, SLOT(close()));

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onApplyButtonClicked()
{
    QKeySequence key = ui->keys->keySequence();
    registerHotkey(key);
}

int MainWindow::registerHotkey(const QKeySequence& ks)
{
    QString str = QString("DeskSwitch%1").arg(ks.toString());
    int id = GlobalAddAtomA(str.toUtf8().constData());
    if (m_hotkeys.contains(id)) {
        return -1;
    }

    uint vk = 0;
    uint modifiers = 0;

    for (int i = 0; i < ks.count(); i++)
    {
        int key = ks[i];
        if (key & Qt::KeyboardModifierMask)
        {
            if (key & Qt::ControlModifier)
            {
                modifiers |= MOD_CONTROL;
            }
            if (key & Qt::AltModifier)
            {
                modifiers |= MOD_ALT;
            }
            if (key & Qt::ShiftModifier)
            {
                modifiers |= MOD_SHIFT;
            }
        }
        vk = key & 0xffU;
        break;
    }

    int ret = RegisterHotKey(0, id, modifiers, vk);
    if (ret)
    {
        m_hotkeys.insert(id, ks);
        return id;
    }
    else
    {
        qDebug() << "Failed to register hotkey";
        GlobalDeleteAtom((ATOM)id);
    }
    return -1;
}

QMyNativeEventFilter::QMyNativeEventFilter(QWidget *widget)
    : m_widget(widget)
{

}

QMyNativeEventFilter::~QMyNativeEventFilter()
{

}

void QMyNativeEventFilter::setWidget(QWidget *w)
{
    m_widget = w;
}

bool QMyNativeEventFilter::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
    if (eventType == "windows_generic_MSG") {
        MSG* msg = reinterpret_cast<MSG*>(message);
        if (WM_HOTKEY == msg->message) {
            uint modifiers = (uint)LOWORD(msg->lParam);
            uint vk = (uint)HIWORD(msg->lParam);
            uint wp = msg->wParam;

            m_widget->activateWindow();
            qDebug() << "nativeEventFilter" << vk << wp << modifiers;
            return true;
        }
    }
    return false;
}
